import { Request, Response } from 'express';
import { CirclePost } from '../models/CirclePost';
import { Circle } from '../models/Circle';
import { User } from '../models/User';
import { CircleComment } from '../models/CircleComment';
import { Op } from 'sequelize';
import { AppError } from '../middleware/errorHandler';

// 创建帖子
export const createPost = async (req: Request, res: Response): Promise<void> => {
    try {
        const { content, images, circleId } = req.body;
        const authorId = (req.user as any).id;

        // 检查圈子是否存在
        const circle = await Circle.findByPk(circleId);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        // 检查是否是圈子成员
        const isMember = await circle.hasMember(authorId);
        if (!isMember) {
            throw new AppError('只有圈子成员才能发帖', 403);
        }

        // 创建帖子
        const post = await CirclePost.create({
            content,
            images,
            authorId,
            circleId,
            likeCount: 0,
            commentCount: 0,
            isTop: false,
            isEssence: false
        });

        // 更新圈子帖子数
        await circle.increment('postCount');

        // 获取完整的帖子信息
        const fullPost = await CirclePost.findByPk(post.id, {
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                }
            ]
        });

        res.success(fullPost, '发帖成功');
    } catch (error) {
        if (error instanceof AppError) {
            throw error;
        }
        throw new AppError('创建帖子失败', 500);
    }
};

// 获取帖子列表
export const getPosts = async (req: Request, res: Response): Promise<void> => {
    try {
        const { circleId } = req.params;
        const { page = 1, limit = 10 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const posts = await CirclePost.findAndCountAll({
            where: { circleId },
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                }
            ],
            order: [
                ['isTop', 'DESC'],
                ['createdAt', 'DESC']
            ],
            limit: Number(limit),
            offset
        });

        res.success({
            posts: posts.rows,
            total: posts.count,
            currentPage: Number(page),
            totalPages: Math.ceil(posts.count / Number(limit))
        });
    } catch (error) {
        throw new AppError('获取帖子列表失败', 500);
    }
};

// 获取帖子详情
export const getPostById = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const post = await CirclePost.findByPk(id, {
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: CircleComment,
                    as: 'comments',
                    include: [
                        {
                            model: User,
                            as: 'author',
                            attributes: ['id', 'username', 'avatar']
                        }
                    ]
                }
            ]
        });

        if (!post) {
            throw new AppError('帖子不存在', 404);
        }

        res.success(post);
    } catch (error) {
        if (error instanceof AppError) {
            throw error;
        }
        throw new AppError('获取帖子详情失败', 500);
    }
};

// 更新帖子
export const updatePost = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const { content, images } = req.body;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            throw new AppError('帖子不存在', 404);
        }

        if (post.authorId !== userId) {
            throw new AppError('只有作者才能编辑帖子', 403);
        }

        await post.update({ content, images });
        res.success(post, '更新成功');
    } catch (error) {
        if (error instanceof AppError) {
            throw error;
        }
        throw new AppError('更新帖子失败', 500);
    }
};

// 删除帖子
export const deletePost = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            throw new AppError('帖子不存在', 404);
        }

        if (post.authorId !== userId) {
            throw new AppError('只有作者才能删除帖子', 403);
        }

        await post.destroy();
        res.success(null, '删除成功');
    } catch (error) {
        if (error instanceof AppError) {
            throw error;
        }
        throw new AppError('删除帖子失败', 500);
    }
};

// 点赞帖子
export const likePost = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            res.status(404).json({ message: '帖子不存在' });
            return;
        }

        // 检查是否已经点赞
        const hasLiked = await post.hasLike(userId);
        if (hasLiked) {
            res.status(400).json({ message: '已经点赞过该帖子' });
            return;
        }

        // 添加点赞
        await post.addLike(userId);
        await post.increment('likeCount');

        res.json({ message: '点赞成功' });
    } catch (error) {
        console.error('点赞帖子失败:', error);
        res.status(500).json({ message: '点赞帖子失败' });
    }
};

// 取消点赞帖子
export const unlikePost = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            res.status(404).json({ message: '帖子不存在' });
            return;
        }

        // 检查是否已经点赞
        const hasLiked = await post.hasLike(userId);
        if (!hasLiked) {
            res.status(400).json({ message: '还没有点赞该帖子' });
            return;
        }

        // 取消点赞
        await post.removeLike(userId);
        await post.decrement('likeCount');

        res.json({ message: '取消点赞成功' });
    } catch (error) {
        console.error('取消点赞帖子失败:', error);
        res.status(500).json({ message: '取消点赞帖子失败' });
    }
};

// 设置帖子置顶
export const setPostTop = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const { isTop } = req.body;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            res.status(404).json({ message: '帖子不存在' });
            return;
        }

        // 检查权限（只有圈子创建者可以设置置顶）
        const circle = await Circle.findByPk(post.circleId);
        if (!circle || circle.creatorId !== userId) {
            res.status(403).json({ message: '没有权限设置帖子置顶' });
            return;
        }

        // 更新置顶状态
        await post.update({ isTop });

        res.json(post);
        return;
    } catch (error) {
        console.error('设置帖子置顶失败:', error);
        res.status(500).json({ message: '设置帖子置顶失败' });
    }
};

// 设置帖子精华
export const setPostEssence = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const { isEssence } = req.body;
        const userId = (req.user as any).id;

        const post = await CirclePost.findByPk(id);
        if (!post) {
            res.status(404).json({ message: '帖子不存在' });
            return;
        }

        // 检查权限（只有圈子创建者可以设置精华）
        const circle = await Circle.findByPk(post.circleId);
        if (!circle || circle.creatorId !== userId) {
            res.status(403).json({ message: '没有权限设置帖子精华' });
            return;
        }

        // 更新精华状态
        await post.update({ isEssence });

        res.json(post);
    } catch (error) {
        console.error('设置帖子精华失败:', error);
        res.status(500).json({ message: '设置帖子精华失败' });
    }
}; 